package Balance;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @Author: 0162977
 * @Date: 2020/12/13 20:03
 */
public class ListenThread implements Runnable{

    DatagramSocket socket = null;
    DatagramPacket packet = null;

    public ListenThread(DatagramSocket socket, DatagramPacket packet) {
        this.socket = socket;
        this.packet = packet;
    }

    @Override
    public void run() {
        String info = null;
        DatagramPacket packet2 = null;
        info = new String(packet.getData(), 0, packet.getLength());

        System.out.println(info);   //接收到的消息
        if (info.split(",")[0].equals("d")) {
            ShareSpaceAndFun.updatePoint(Integer.parseInt(info.split(",")[1]),Integer.parseInt(info.split(",")[2]));
        }else{
            try {
                InetAddress address = null;
                address = InetAddress.getByName("localhost");
                byte[] data2 = info.getBytes();
                packet2 = new DatagramPacket(data2, data2.length, address, ShareSpaceAndFun.chooseRoot());
                socket.send(packet2);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
